package com.shadt.cloud.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.shadt.cloud.dao.BranchChannelDao;
import com.shadt.cloud.dao.BranchDao;
import com.shadt.cloud.dao.ChannelDao;
import com.shadt.cloud.entity.CloudBranch;
import com.shadt.cloud.entity.CloudBranchChannel;
import com.shadt.cloud.service.BranchChannelService;
import com.shadt.cloud.vo.ChannelVo;

/**
 * 分平台权限业务逻辑层接口
 * 
 * @author SongR
 *
 */
@Service
public class BranchChannelServiceImpl implements BranchChannelService {

	@Autowired
	BranchChannelDao dao;
	@Autowired
	BranchDao bdao;
	@Autowired
	ChannelDao cdao;

	/**
	 * 添加栏目权限
	 */
	@SuppressWarnings("rawtypes")
	public boolean add(String branchid, String key) {
		ChannelVo cvo = new ChannelVo();
		String hqlc = "select * from community_channel where isenable = 1 and channelKey ='" + key + "'";
		List l = cdao.getBySql(hqlc);
		Iterator it = l.iterator();
		List<ChannelVo> vos = new ArrayList<ChannelVo>();
		while (it.hasNext()) {
			Map m = (Map) it.next();
			ChannelVo vo = new ChannelVo();
			vo.setId(m.get("seq").toString());
			vo.setName(m.get("title").toString());
			vo.setKey(m.get("channelkey").toString());
			vos.add(vo);
		}
		cvo = vos.get(0);
		String hql = "from CloudBranchChannel where key='" + key + "' and branchid='" + branchid + "'";
		CloudBranchChannel bc = dao.get(hql);
		if (null != cvo && null == bc) {
			bc = new CloudBranchChannel();
			bc.setBranchid(new Long(branchid));
			bc.setKey(key);
			bc.setName(cvo.getName());
			bc.setCreattime(new Date());
			bc.setStatus(1);
			dao.save(bc);
		} else {
			bc.setStatus(1);
			return false;
		}
		return true;
	}

	/**
	 * 验证分平台是否有此栏目数据获取权限
	 */
	public boolean check(String key, String appname) {
		CloudBranch b = bdao.get("from CloudBranch where status=0 and name='" + appname + "'");
		CloudBranchChannel bc = null;
		if (null != b)
			bc = dao.get(
					"from CloudBranchChannel where status=0 and branchid='" + b.getId() + "' and key='" + key + "'");
		if (null != bc) {
			return true;
		} else
			return false;
	}
}
